package com.business.async;


import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @Description: TODO
 * @Author: mis_wu
 * @Date: 2022/7/6
 * 异步组件测试类
 * <a href="https://www.bilibili.com/video/BV1Q64y1f7fX?p=38&spm_id_from=pageDriver&vd_source=0775c3e59510d942e0897cfffea682c0">https://www.bilibili.com/video/BV1Q64y1f7fX?p=38&spm_id_from=pageDriver&vd_source=0775c3e59510d942e0897cfffea682c0</a>
 **/
@Component
@Slf4j
public class TestAsync {

    private static final Long PERIOD = 3L;

    /**
     * 整合线程池,@Async("taskExecutor")
     * taskExecutor：线程池名称
     */
    @Async("taskExecutor")
    public void testAsync() {
        log.info("测试异步方法进入...");
        try {
//            Thread.sleep(3000);
            //TimeUnit.SECONDS.sleep(3);
            ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
            //https://www.cnblogs.com/acm-bingzi/p/spring_delay.html
            executorService.schedule(TestAsync::test, PERIOD, TimeUnit.SECONDS);
            //executorService.scheduleAtFixedRate(TestAsync::test, 0, PERIOD, TimeUnit.DAYS);
            log.info("当前线程:{},返回值:{}",Thread.currentThread().getName(),"一般没有返回值");
            /*
             * do something
             * 1、延迟执行1:线程睡眠
             * 2、scheduleAtFixedRate
             */
        }catch (Exception e){
            e.printStackTrace();
        }
        log.info("测试异步方法结束...");
    }

    public static String test(){
        log.info("异步静态方法 start...");
        log.info("线程:{}",Thread.currentThread().getName());
        log.info("异步静态方法 end...");
        return "hello async";
    }
}
